package com.xdqzy.baseline.common.config;

import com.xdqzy.baseline.common.constant.ResultCodeEnum;
import com.xdqzy.baseline.common.model.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author dengmawei
 * @version 1.0.0
 * @ClassName GlobalExceptionHandler.java
 * @Description TODO
 * @createTime 2020年10月24日 16:22:00
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 处理BindException
     * @param req 请求
     * @param res 响应
     * @param e 异常
     * @throws IOException IOException
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public RestResult dataBindException(BindException e) {
        ObjectError bindError = e.getBindingResult().getAllErrors().get(0);
        log.warn("param format is error:{}", bindError.getDefaultMessage());
        RestResult restResult = RestResult.buildFail(ResultCodeEnum.PARAM_ERROR.getCode(), ResultCodeEnum.PARAM_ERROR.getErrorMsg());
        return restResult;
    }

    /**
     * 处理通用异常
     * @param e 异常
     * @return RestResult
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public RestResult customException(Exception e) {
        log.error("receive system custom error", e);
        RestResult restResult = RestResult.buildFail(ResultCodeEnum.SERVER_INNER_ERROR.getCode(),
                ResultCodeEnum.SERVER_INNER_ERROR.getErrorMsg());
        return restResult;
    }
}
